package com.nj.liandi.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nj.liandi.common.utils.HttpUtils;
import com.nj.liandi.gulimall.member.dao.MemberLevelDao;
import com.nj.liandi.gulimall.member.entity.MemberLevelEntity;
import com.nj.liandi.gulimall.member.exception.PhoneExistException;
import com.nj.liandi.gulimall.member.exception.UserNameExistException;
import com.nj.liandi.gulimall.member.vo.MemberLoginVo;
import com.nj.liandi.gulimall.member.vo.MemberRigistVo;
import com.nj.liandi.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nj.liandi.common.utils.PageUtils;
import com.nj.liandi.common.utils.Query;

import com.nj.liandi.gulimall.member.dao.MemberDao;
import com.nj.liandi.gulimall.member.entity.MemberEntity;
import com.nj.liandi.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRigistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        MemberLevelEntity levelEntity=memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        checkPhoneUnique(vo.getPhone());
        checkPhoneUnique(vo.getUserName());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        memberDao.insert(entity);
    }

    @Override
    public void checkUsernameUnique(String userName) throws UserNameExistException{
        MemberDao memberDao = this.baseMapper;
        Integer username = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username>0){
            throw new UserNameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile >0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginacct()).or().eq("mobile", vo.getLoginacct()));
        if (entity!=null) {
            String password = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(vo.getPassword(),password);
            if (matches){
                return entity;
            }else {
                return null;
            }
        }else {
            return null;
        }
    }

    @Override
    public MemberEntity login(SocialUser user) throws Exception {
        String uid = user.getUid();
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity!=null) {
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(user.getAccess_token());
            entity.setExpiresIn(user.getExpires_in());
            memberDao.updateById(entity);

            memberEntity.setAccessToken(user.getAccess_token());
            memberEntity.setExpiresIn(user.getExpires_in());
            return memberEntity;
        }else {
            MemberEntity regist = new MemberEntity();
            try {
                Map<String,String> query = new HashMap<>();
                query.put("access_token",user.getAccess_token());
                query.put("uid",user.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
                if (response.getStatusLine().getStatusCode()==0) {
                    String s = EntityUtils.toString(response.getEntity());
                    JSONObject parseObject = JSON.parseObject(s);
                    String name = parseObject.getString("name");
                    String gender = parseObject.getString("gender");

                    regist.setNickname(name);
                    regist.setGender("m".equals(gender)?1:0);

                }
            }catch (Exception e){}
            regist.setSocialUid(user.getUid());
            regist.setAccessToken(user.getAccess_token());
            regist.setExpiresIn(user.getExpires_in());
            memberDao.insert(regist);
            return regist;
        }
    }


}